<?php

namespace app\controller\backed;

use app\BaseController;
use app\lib\exception\NotFoundException;
use think\facade\Config;
use think\facade\Cache;
use app\model\Candidate as CandidateModel;
use app\model\Character as CharacterModel;
use app\model\CandidateComment as CandidateCommentModel;
use app\model\DingGroup as DingGroupModel;
use app\model\DingUser as DingUserModel;
use app\service\DingNotice as DingNoticeService;

class DingEvent
{
    public $attendees;
    public $description;
    public $summary;
    public $calendar_id = 'primary';
    public $organizer = [];
    public $reminder = [
        'method' => 'app',
        'minutes' => 15
    ];
    public $event_id;
    public $end = [];
    public $start = [];
    public $location = [];
}

class Candidate extends BaseController
{

    public function getCandidateComments()
    {
        $params = request()->param();

        $candidateCommentModel = new CandidateCommentModel();

        $pageNo = isset($params['pageNo']) ? $params['pageNo'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 20;

        $where = [];
        if(isset($params['candidate_name'])){
            $where[] = ['candidate_name', 'like','%' . $params['candidate_name'] . '%'];          
        }
        if(isset($params['interview_name'])){
            $where[] = ['interview_name', 'like','%' . $params['interview_name'] . '%'];
        }

        if(isset($params['interview_name'])){
            $where[] = ['interview_name', 'like','%' . $params['interview_name'] . '%'];
        }
        

        if(isset($params['hr_name'])){
            $where[] = ['hr_name', 'like','%' . $params['hr_name'] . '%'];
        }

        $res = CandidateCommentModel::where($where)->paginate([
            'page' => $pageNo,
            'list_rows' => $pageSize
        ],false);

        return $this->successMessage('查询成功',$res);
    }

    // 候选人列表
    public function getCandidates()
    {
        $params = request()->param();

        $candidateModel = new CandidateModel();
        $characterModel = new CharacterModel();
        
        $status = isset($params['status']) ? $params['status'] : '';
        $pageNo = isset($params['pageNo']) ? $params['pageNo'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 20;

        $where = [];
        if(!empty($status)){
            $where['status'] = [$status];            
        }

        if(isset($params['realname'])){
            $where[] = ['realname', 'like','%' . $params['realname'] . '%'];
        }

        if(isset($params['group'])){
            $where[] = ['group', 'like','%' . $params['group'] . '%'];
        }

        if(isset($params['hr'])){
            // $where['hr'] = [$params['hr']];  
            $where[] = ['hr', 'like','%' . $params['hr'] . '%'];
        }
    
    
        if(isset($params['organizer'])){
            // $where['hr'] = [$params['hr']];
            $where[] = ['organizer', 'like','%' . $params['organizer'] . '%'];
        }

        $res = CandidateModel::where($where)->order('id desc')->paginate([
            'page' => $pageNo,
            'list_rows' => $pageSize
        ],false)->toArray();
        
        
        // 性格测试
        $characterModel = new CharacterModel();
        foreach ($res['data'] as $key => &$item) {
            $chara = $characterModel->where(['user_id' => $item['id']])->find();
            $data = [
                'd' => $chara['d'],
                'i' => $chara['i'],
                's' => $chara['s'],
                'c' => $chara['c'],
            ];

            $item['character'] = calcDISC($data);
            $item['group_name'] = DingGroupModel::find($item['group'])['name'];
        }

        return $this->successMessage('查询成功',$res);
    }

    // 创建候选人
    public function createCandidate()
    {       

        $params = request()->param();
        $groups = explode(',', $params['group_location']);
        $interview_date = date('Y-m-d H:i:s',strtotime($params['interview_date']));

        $data = [
        	'realname' => $params['realname'],
			'mobile' => $params['mobile'],
			'interview_date' => $interview_date,
			'worker' => $params['worker'],
            'remark' => $params['remark'],
            'status' => $params['status'],
            'group' => array_pop($groups),
            'address' => $params['address'],
            'group_location' => $params['group_location'],
            'group_interview' => $params['group_interview'],
            'hr' => $params['hr'],
            'organizer' => $params['organizer'] ? $params['organizer'] : $params['hr']
        ];

        
//        面试流程负责人[选填] 不填写时默认为面试HR   字段: organizer
        
        


        $ding_params = [
            "title" =>  'HR Online消息通知',
            "text" => "您好，".$params['group_interview']." 有一名候选人".$params['realname']."在".$interview_date."需要您去负责面试，请留意。",
        ];

        $dingUserModel = new DingUserModel();
        $dingNoticeService = new DingNoticeService;
        $user = $dingUserModel->where(['name' => $params['group_interview']])->find();
        if($user){
            $dingNoticeService->companyMsg($user['id'],'markdown',$ding_params);
        }

        // hr
        $hr = $dingUserModel->where(['name' => $params['hr']])->find();


        // 面试官
        $group = $dingUserModel->where(['name' => $params['group_interview']])->find();

        // 流程负责人
        $organizer = null;
        if ($params['organizer']) {
            $organizer = $dingUserModel->where(['name' => $params['organizer']])->find();
        }
    
        

        if ($params['status'] == 0) {
            $attendees = [
                [
                    'userid' =>$hr['id']
                ],
                [
                    'userid' =>$group['id']
                ]
            ];

            if ($organizer['id']) {
                array_push($attendees,['userid' => $organizer['id']]);
            }

//            $attendees = [
//                'userid' => '033514694921936883',
//                'userid' =>  '15857033069202998'
//            ];

            $dingGroupModel = new DingGroupModel();
            $where[] = ['id', 'in', $params['group_location']];
            $groupArray = $dingGroupModel->field('name')->where($where)->select();

            $groupName = '';
            foreach ($groupArray as $v) {
                $groupName = $groupName ?  $groupName.'/'.$v['name'] : $v['name'];
            }

            $event = new DingEvent();
            $event->summary = $groupName." ".$params['realname']." 面试";
            $event->attendees = $attendees;

            $event->start['timestamp'] = strtotime($params['interview_date']);
            $event->end['timestamp'] = strtotime($params['interview_date']);

            // 组织人 hr
            $event->organizer['userid'] = $organizer['id'] ? $organizer['id'] :  $hr['id']; // $hr['id']
            $remark = $params['remark']?" 备注: ".$params['remark']:'';
            $event->description = "岗位: ".$params['worker'].$remark;
            $event->location['place'] = $params['address'];

            $dingResult = $dingNoticeService->calendarCreate($event);
            // 更新候选人的event_id

            $data['event_id'] = $dingResult['result']['event_id'];
        }


        $candidateModel = new CandidateModel();
        $candidateModel->save($data);

        return $this->successMessage('创建成功');

    }


    public function updateCandidate()
    {

        $params = request()->param();
        $groups = explode(',', $params['group_location']);

        $interview_date = date('Y-m-d H:i:s',strtotime($params['interview_date']));

        $info = CandidateModel::find($params['id']);

        $data = [
        	'realname' => $params['realname'],
			'mobile' => $params['mobile'],
			'interview_date' => $interview_date,
            'group' => array_pop($groups),
			'status' => $params['status'],
            'remark' => $params['remark'],
            'address' => $params['address'],
            'group_location' => $params['group_location'],
            'group_interview' => $params['group_interview'],
            'hr' => $params['hr'],
            'organizer' => $params['organizer'],
			'update_time' => time(),
        ];




        // $ding_params = [
        //     "title" =>  'HR Online消息通知',
        //     "text" => "您好，".$params['group_interview']." 有一名候选人".$params['realname']."在".$interview_date."需要您去负责面试，请留意。",
        // ];

        // $dingUserModel = new DingUserModel();
        // $dingNoticeService = new DingNoticeService;
        // $user = $dingUserModel->where(['name' => $params['group_interview']])->find();

        // if($user && $params['status'] != $info['status']){
        //     $dingNoticeService->companyMsg($user['id'],'markdown',$ding_params);
        // }

        // 实例化钉钉服务
        $dingUserModel = new DingUserModel();
        $dingNoticeService = new DingNoticeService;

        // hr
        $hr = $dingUserModel->where(['name' => $params['hr']])->find();
        // 面试官
        $group = $dingUserModel->where(['name' => $params['group_interview']])->find();
    
        $organizer = null;
        if ($params['organizer'] != $params['hr']) {
            $organizer = $dingUserModel->where(['name' => $params['organizer']])->find();
        }

        if($info['event_id']) {
            // 修改日程  不改变面试状态   不能变更组织人和新增组织人
            if ($params['status'] == '0' || $params['status'] == '面试中') {
                $attendees = [
                    'attendee_status' => 'add',
                    'userid' =>$hr['id'],
                    'userid' =>$group['id']
                ];

//                $attendees = [
//                    'userid' => '033514694921936883',
//                    'userid' =>  '15857033069202998',
//                    'attendee_status' => 'add'
//                ];

                $dingGroupModel = new DingGroupModel();
                $where[] = ['id', 'in', $params['group_location']];
                $groupArray = $dingGroupModel->field('name')->where($where)->select();
                
                // 当hr 或者 面试官有变更执行接口
                if ($params['hr'] != $info['hr'] || $params['group_interview'] != $info['group_interview']) {
    
                    // TODO: 可以变更  hr  面试官    取消参会人+新增参会人
                    // 判断是否变更hr
                    $rmAttendees = [
                        'attendee_status' => 'remove'
                    ];
                    $newAttendees = [
                        'attendee_status' => 'add'
                    ];
                    
                    if ($params['hr'] != $info['hr']) {
                        // 删除的参会人
                        array_push($rmAttendees, ['userid' => $info['hr']]);
        
                        // 新增的参会人
                        array_push($newAttendees, ['userid' => $params['hr']]);
                    }
    
                    if ($params['group_interview'] != $info['group_interview']) {
                        // 删除的参会人
                        array_push($rmAttendees, ['userid' => $info['group_interview']]);
        
                        // 新增的参会人
                        array_push($newAttendees, ['userid' => $params['group_interview']]);
                    }
                    
                    
                   $deres=  $dingNoticeService->changeAttendees($info['event_id'], $rmAttendees); // 删除参会人
//                    var_dump($deres);
//                    $dingNoticeService->changeAttendees($info['event_id'], $newAttendees); // 新增参会人
                }
                
//                var_dump($attendees);

                $groupName = '';
                foreach ($groupArray as $v) {
                    $groupName = $groupName ?  $groupName.'/'.$v['name'] : $v['name'];
                }

                $event = new DingEvent();
                $event->summary = $groupName." ".$params['realname']." 面试";
                $event->attendees = $attendees;

                $event->start['timestamp'] = strtotime($params['interview_date']);
                $event->end['timestamp'] = strtotime($params['interview_date']);

                // 组织人 hr
                $event->organizer['userid'] = $organizer['id'] ? $organizer['id'] : $hr['id']; // $hr['id']
                $remark = $params['remark']?" 备注: ".$params['remark']:'';
                $event->description = "岗位: ".$params['worker'].$remark;
                $event->event_id = $info['event_id'];
                $event->location['place'] = $params['address'];

                $dingResult = $dingNoticeService->calendarUpdate($event);
                var_dump($dingResult);
            }else {
                // 修改其他状态  非面试中   取消日程
                $res = $dingNoticeService->calendarDelete($info['event_id']);
                $data['event_id'] = null;
            }
        }else {
            // 新建日程
            if ($params['status'] == 0) {
                $attendees = [
                    [
                        'userid' => $hr['id']
                    ],
                    [
                        'userid' => $group['id']
                    ]
                ];
    
                if ($organizer['id']) {
                    array_push($attendees,['userid' => $organizer['id']]);
                }

//                $attendees = [
//                    'userid' => '033514694921936883',
//                    'userid' =>  '15857033069202998'
//                ];

                $dingGroupModel = new DingGroupModel();
                $where[] = ['id', 'in', $params['group_location']];
                $groupArray = $dingGroupModel->field('name')->where($where)->select();

                $groupName = '';
                foreach ($groupArray as $v) {
                    $groupName = $groupName ?  $groupName.'/'.$v['name'] : $v['name'];
                }

                $event = new DingEvent();
                $event->summary = $groupName." ".$params['realname']." 面试";
                $event->attendees = $attendees;

                $event->start['timestamp'] = strtotime($params['interview_date']);
                $event->end['timestamp'] = strtotime($params['interview_date']);

                // 组织人 hr
                $event->organizer['userid'] = $organizer['id'] ? $organizer['id'] : $hr['id']; // $hr['id']
                $remark = $params['remark']?" 备注: ".$params['remark']:'';
                $event->description = "岗位: ".$params['worker'].$remark;
                $event->location['place'] = $params['address'];

                $dingResult = $dingNoticeService->calendarCreate($event);
                // 更新候选人的event_id

                $data['event_id'] = $dingResult['result']['event_id'];
            }
        }


        $candidateModel = new CandidateModel();
        $candidateModel->update($data, ['id' => $params['id']]);

        return $this->successMessage('修改成功');
    }


    public function getAddressList()
    {
        $params = request()->param();
        $address = $params['name'];
        $list = file_get_contents('http://map.baidu.com/su?wd='.$address.'&cid=131&type=0&t=1590821243824&from=jsapi');
        $res = json_decode($list,true)['s'];

        foreach ($res as $key => &$item) {
            $item = explode('$268$', $item)[0];
            $item = str_replace('$', '', $item);
        }

        return $this->successMessage('修改成功',$res);

    }


    public function deleteCandidate()
    {

        $params = request()->param();

        $info = CandidateModel::find($params['id']);

        // 实例化钉钉服务
        $dingUserModel = new DingUserModel();
        $dingNoticeService = new DingNoticeService;

        // 删除员工 任何状态都 取消日程
        if ($info['event_id']) {
            $dingNoticeService->calendarDelete($info['event_id']);
        }

        CandidateModel::destroy($params['id']);
        
        return $this->successMessage('删除成功');
    }

//    // 清洗面试地址
//    public function address()
//    {
//        $candidateModel = new CandidateModel();
//        $sql = "UPDATE `candidate` SET `address` = '郑州市金水区楷林国际4层' WHERE `address` = '郑州市金水区格拉姆商务大厦A座26层'";
//        $candidateModel->execute($sql);
//        return $this->successMessage('清除成功');
//    }
//
//    // 清空性格测试表
//    public function testclear()
//    {
//        $characterModel = new CharacterModel();
//        $sql = "truncate table character";
//        $res = $characterModel->select();
//        $characterModel->where('Id',5)->delete(true);
//        return $this->successMessage('清除成功',$res);
//    }

}